from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from django.db.models import Q
from enterprise_sys.models import Enterprise, Enterprise_Usr, Employee_info
from chat_sys.models import *
from utils.response_utils import *
from utils.session_utils import *
from utils.time_utils import *


@csrf_exempt
def get_unread_count(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if has_login(request):
        user: User = get_login_user(request)
    else:
        return build_response(errno=2001, msg='用户未登录')
    query = Message.objects.filter(receiver=user, set_read=False)
    return build_response(other_info={"count": query.count()}, msg="获取成功")


@csrf_exempt
def get_one_msg_list(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if has_login(request):
        user: User = get_login_user(request)
    else:
        return build_response(errno=2001, msg='用户未登录')
    counterpart_user_id = request.GET.get('userId')
    query = User.objects.filter(id=counterpart_user_id)
    if query.count() == 0:
        return build_response(errno=2002, msg='与该用户聊天的用户不存在')
    counterpart_user = query[0]
    msg_instance_list = Message.objects.filter(Q(sender=user, receiver=counterpart_user) |
                                               Q(sender=counterpart_user, receiver=user)).order_by("send_time")
    msg_instance_list.update(set_read=True)
    msg_list = []
    for msg in msg_instance_list:
        msg_dict = msg.parse_dict()
        if 'type' in msg_dict:
            del msg_dict['type']
        msg_list.append(msg_dict)
    return build_response(other_info={"message_list": msg_list})


@csrf_exempt
def get_msg_list(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if has_login(request):
        user: User = get_login_user(request)
    else:
        return build_response(errno=2001, msg='用户未登录')
    return_info = {}
    result_list = []
    senders = Message.objects.filter(receiver=user).values_list('sender_id', flat=True).distinct()
    receivers = Message.objects.filter(sender=user).values_list('receiver_id', flat=True).distinct()
    chat_partners = User.objects.filter(
        Q(id__in=senders) | Q(id__in=receivers)
    ).distinct()
    if "selected_user_id" in request.GET:
        chat_partners = User.objects.filter(
            Q(id__in=senders) | Q(id__in=receivers) | Q(id=request.GET['selected_user_id'])
        ).distinct()
    else:
        chat_partners = User.objects.filter(
            Q(id__in=senders) | Q(id__in=receivers)
        ).distinct()
    for chat_partner in chat_partners:
        user_info = chat_partner.info_to_dict()
        query = Enterprise_Usr.objects.filter(usr=chat_partner)
        enterprise_info = {}
        if query.count() != 0:
            e_u_instance = query[0]
            enterprise_info = {
                "enterprise_id": e_u_instance.enterprise.id,
                "enterprise_name": e_u_instance.enterprise.name,
                "is_admin": e_u_instance.is_admin
            }
        last_message_instance = Message.objects.filter(Q(sender=user, receiver=chat_partner) |
                                                       Q(sender=chat_partner, receiver=user)).order_by("-send_time")
        unread_count = last_message_instance.filter(set_read=False, receiver=user).count()
        if last_message_instance.count() == 0:
            last_message = {}
        else:
            last_message = last_message_instance[0].parse_dict()
        result_list.append({
            "user": user_info,
            "enterprise": enterprise_info,
            "last_message": last_message,
            "unread_count": unread_count
        })
    return_info['result_list'] = result_list
    return build_response(other_info=return_info, msg="success")
